/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Ventas.java
 *
 * Created on 17/02/2011, 06:03:07 PM
 */

package puntodeventa;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import net.sf.jasperreports.engine.JRException;

/**
 *
 * @author KaNo
 */
public class Ventas extends javax.swing.JFrame {

    private DefaultTableModel modelo = new DefaultTableModel();

    /** Creates new form Ventas */
    public Ventas() {
        initComponents();
        modelo = (DefaultTableModel) this.jTable1.getModel();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jTextField4 = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jTextField5 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel8 = new javax.swing.JLabel();
        jTextField6 = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel5 = new javax.swing.JLabel();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel2.setText("Articulo");
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 30, -1, -1));

        jLabel3.setText("Precio");
        getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 30, -1, -1));

        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });
        getContentPane().add(jTextField1, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 50, 140, -1));
        getContentPane().add(jTextField2, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 50, 50, -1));

        jLabel4.setText("Cant");
        getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 30, -1, -1));

        jTextField3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField3ActionPerformed(evt);
            }
        });
        getContentPane().add(jTextField3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 50, 30, -1));

        jLabel6.setText("Efectivo");
        getContentPane().add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 430, -1, -1));

        jTextField4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField4ActionPerformed(evt);
            }
        });
        getContentPane().add(jTextField4, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 450, 90, -1));

        jLabel7.setText("Su Cambio");
        getContentPane().add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 430, -1, -1));
        getContentPane().add(jTextField5, new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 450, 90, -1));

        jButton1.setText("Cobrar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 490, -1, -1));

        jButton2.setText("Listar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 140, 70, -1));

        jLabel8.setText("Total");
        getContentPane().add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(470, 430, -1, -1));
        getContentPane().add(jTextField6, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 450, 100, -1));

        jTable1.setBackground(new java.awt.Color(204, 0, 0));
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Clave", "Cantidad", "Nombre", "Precio", "Total"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 90, 360, 200));

        jLabel5.setText("En Venta");
        getContentPane().add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 50, -1, -1));

        jButton3.setText("Eliminar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 170, -1, -1));

        jButton4.setText("Nueva Venta");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton4, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 200, -1, -1));

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/i love motivos.JPG"))); // NOI18N
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 560, -1));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTextField4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField4ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField4ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
       
        try{
            Class.forName("org.gjt.mm.mysql.Driver");
        }catch(ClassNotFoundException ex){
            ex.printStackTrace();
        }
        //Fin de la carga Driver

        //Conexion a la BD
        try{
            Connection c=(Connection)DriverManager.getConnection("jdbc:mysql://localhost/Punto_de_Venta","root","root");
            Statement sql=(Statement)c.createStatement();
            String sqlQuery = "Select clave,nombre,precio from almacen where nombre = '"+this.jTextField1.getText().trim()+"'";

            ResultSet datos = sql.executeQuery(sqlQuery);
            if (!datos.first()){
                JOptionPane.showMessageDialog(null,"El producto no existe", "Error en la busqueda",JOptionPane.ERROR_MESSAGE);
            }else{
                
                try {
                       datos.first();

                       if (datos.getRow()==1){
          // Se crea un array que será una de las filas de la tabla.

          // Se rellena cada posición del array con una de las columnas de la tabla en base de datos.
          // El primer indice en data es el 1, no el cero, por eso se suma 1.

         String [] fila = {datos.getObject(1).toString(),this.jTextField3.getText(),datos.getObject(2).toString(),
         datos.getObject(3).toString(),
         Float.parseFloat(this.jTextField3.getText())*Float.parseFloat(datos.getObject(3).toString())+""};



         // Se añade al modelo la fila completa.
         modelo.addRow(fila);
         sumar();
                       }
        this.jTable1.setModel(modelo);
        } catch (Exception ex) {

        Logger.getLogger(Administrador.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }catch (SQLException ex){

            ex.printStackTrace();
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jTextField3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField3ActionPerformed
        // TODO add your handling code here:
        
    }//GEN-LAST:event_jTextField3ActionPerformed

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
        // TODO add your handling code here:

    }//GEN-LAST:event_jTextField1ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        int fila = jTable1.getSelectedRow();
        if (fila > -1){
            modelo.removeRow(fila);
            sumar();
        }else{
            JOptionPane.showMessageDialog(null,"Seleccione un producto", "Error en eliminacion",JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        
        this.jTextField5.setText(Float.parseFloat(this.jTextField4.getText())-
                Float.parseFloat(this.jTextField6.getText())+"");
        insertarVentas();

         try{
            Class.forName("org.gjt.mm.mysql.Driver");
        }catch(ClassNotFoundException ex){
            ex.printStackTrace();
        }

        //Fin de la carga Driver

        //Conexion a la BD
        try{
            Connection c=(Connection)DriverManager.getConnection("jdbc:mysql://localhost/Punto_de_Venta","root","root");
            Statement sql=(Statement)c.createStatement();
            int filas = modelo.getRowCount();
            for (int i=0;i<filas;i++){
                String clave = modelo.getValueAt(i, 0).toString();
                String cantidad = modelo.getValueAt(i, 1).toString();
                String nombre = modelo.getValueAt(i, 2).toString();
                String precio = modelo.getValueAt(i, 3).toString();
                String sqlQuery;
                ResultSet datos;

                sqlQuery = "Insert Into ticket (clave,nombre,precio,cantidad) " +
                       "values('"+clave+"','"+nombre+"','"+precio+"','"+cantidad+"')";
                sql.executeUpdate(sqlQuery);
                 
         }
        }catch (SQLException ex){

            ex.printStackTrace();
        }


        try {
            Ticket.tick();
        } catch (JRException ex) {
            Logger.getLogger(Ventas.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(Ventas.class.getName()).log(Level.SEVERE, null, ex);
        }

         try{
            Class.forName("org.gjt.mm.mysql.Driver");
        }catch(ClassNotFoundException ex){
            ex.printStackTrace();
        }

        //Fin de la carga Driver

        //Conexion a la BD
        try{
            Connection c=(Connection)DriverManager.getConnection("jdbc:mysql://localhost/Punto_de_Venta","root","root");
            Statement sql=(Statement)c.createStatement();
               
                sql.executeUpdate("delete from ticket");

         
        }catch (SQLException ex){

            ex.printStackTrace();
        }

    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        // TODO add your handling code here:
        int filas = modelo.getRowCount();
        for (int i=filas-1;i>=0;i--){
            modelo.removeRow(i);
            Ventas ven = new Ventas();
            ven.setVisible(true);
            this.dispose();
        }
    }//GEN-LAST:event_jButton4ActionPerformed

    public void sumar(){
        float total=0;
        for (int i=0;i<modelo.getRowCount();i++){
            total += Float.parseFloat(modelo.getValueAt(i,4).toString());
        }
        this.jTextField6.setText(total+"");
    }

    private void insertarVentas() {
        try{
            Class.forName("org.gjt.mm.mysql.Driver");
        }catch(ClassNotFoundException ex){
            ex.printStackTrace();
        }

        //Fin de la carga Driver

        //Conexion a la BD
        try{
            Connection c=(Connection)DriverManager.getConnection("jdbc:mysql://localhost/Punto_de_Venta","root","root");
            Statement sql=(Statement)c.createStatement();
            int filas = modelo.getRowCount();
            for (int i=0;i<filas;i++){
                String clave = modelo.getValueAt(i, 0).toString();
                String cantidad = modelo.getValueAt(i, 1).toString();
                String nombre = modelo.getValueAt(i, 2).toString();
                String precio = modelo.getValueAt(i, 3).toString();
                String sqlQuery;
                ResultSet datos;
                sqlQuery = "Update almacen Set cantidad = (cantidad - " +cantidad+ ") " +
                       "where clave=" + clave;
                sql.executeUpdate(sqlQuery);
                sqlQuery = "Insert Into vendido (clave,nombre,precio,cantidad) " +
                       "values('"+clave+"','"+nombre+"','"+precio+"','"+cantidad+"')";
                sql.executeUpdate(sqlQuery);     
            }
        }catch (SQLException ex){

            ex.printStackTrace();
        }
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Ventas().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    private javax.swing.JTextField jTextField6;
    // End of variables declaration//GEN-END:variables

}
